<?php declare(strict_types=1);

namespace PinWuYun\domain\helper;

use Exception;
use GuzzleHttp\Exception\GuzzleException;
use PinWuYun\domain\dao\OrderRelationDao;
use PinWuYun\domain\data\YouZanData\OrderData;
use PinWuYun\domain\service\starLinkServer\Order;
use PinWuYun\domain\service\youZanServer\LogServer;
use PinWuYun\domain\service\youZanServer\OrderServer;
use PinWuYun\domain\service\youZanServer\TokenServer;

/**
 * Created: by zhiJie
 * Date: 2021/6/30
 */
class OrderHelper
{
    private $data;
    private $service;
    public function __construct()
    {
        $this->data = new OrderData();
        $this->service = (new OrderServer);
    }

    /**
     * 星链发货通知，同步到有赞去
     * @param array $params
     * @throws Exception
     * @throws GuzzleException
     */
    public function sendGoodsAction(array $params)
    {
        $token = TokenServer::getAccessToken();
        $relation = (new OrderRelationDao)->getOneByOrderSn($params['orderSn']);
        // 获取星链订单详情
        $starOrderInfo = json_decode((new Order)->findExpressInfoByOrderSn(['orderSn' =>$params['orderSn']])
            ->getBody()->getContents(),true);
        if($starOrderInfo['code'] != 0) {
            LogServer::errLog('---------------获取不错物流信息--------------'.PHP_EOL);
            LogServer::errLog($params);
            throw new Exception('获取不到物流信息');
        }
        $requestParams = $this->data->buildConfirmSeenData($relation['you_tid'], $starOrderInfo['data']['deliveryNo']);
        $this->service->confirmedSend($requestParams, $token);
    }

    /**
     * 星链确认收货，交易完成了。同步到有赞
     * @throws Exception
     */
    public function sendTradeFinishAction(array $params)
    {
        $relation = (new OrderRelationDao)->getOneByOrderSn($params['orderSn']);
        // 有赞确认收货  openID 待填充 TODO
        $params = $this->data->buildTradeFinish($relation['you_tid'], '');
        $this->service->confirmedReceive($params);
    }


}